﻿using UnityEngine;

namespace ETModel {

    public static class MatrixHelper {

        /// <summary>
        /// 按照Unity的用法,提取出旋转四元数
        /// </summary>
        /// <param name="matrix"></param>
        /// <returns></returns>
        public static Quaternion ExtractRotationForU3d(ref this Matrix4x4 matrix) {
            Vector3 forward;
            forward.x = matrix.m02;
            forward.y = matrix.m12;
            forward.z = matrix.m22;

            Vector3 upwards;
            upwards.x = matrix.m01;
            upwards.y = matrix.m11;
            upwards.z = matrix.m21;

            return Quaternion.LookRotation(forward, upwards);
        }

        /// <summary>
        /// 按照Unity的用法,提取出位置
        /// </summary>
        /// <param name="matrix"></param>
        /// <returns></returns>
        public static Vector3 ExtractPositionForU3d(ref this Matrix4x4 matrix) {
            Vector3 position;
            position.x = matrix.m03;
            position.y = matrix.m13;
            position.z = matrix.m23;
            return position;
        }
        /// <summary>
        /// 按照Unity的用法,将位置信息设置到矩阵中
        /// </summary>
        /// <param name="position"></param>
        public static void SetPositionForU3d(ref this Matrix4x4 matrix, ref Vector3 position) {
            matrix.m03 = position.x;
            matrix.m13 = position.y;
            matrix.m23 = position.z;
        }

        /// <summary>
        /// 按照Unity的用法,提取出缩放值
        /// </summary>
        /// <param name="matrix"></param>
        /// <returns></returns>
        public static Vector3 ExtractScaleForU3d(ref this Matrix4x4 matrix) {
            Vector3 scale;
            scale.x = new Vector4(matrix.m00, matrix.m10, matrix.m20, matrix.m30).magnitude;
            scale.y = new Vector4(matrix.m01, matrix.m11, matrix.m21, matrix.m31).magnitude;
            scale.z = new Vector4(matrix.m02, matrix.m12, matrix.m22, matrix.m32).magnitude;
            return scale;
        }


    }
}
